import os
import logging
from weasyprint import HTML
from datetime import datetime

logger = logging.getLogger(__name__)

class PDFService:
    def __init__(self, token=None, cookie=None, fakeid=None):
        """初始化PDF服务
        
        Args:
            token (str, optional): 微信token
            cookie (str, optional): 微信cookie
            fakeid (str, optional): 微信fakeid
        """
        self.pdf_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'data', 'pdfs')
        os.makedirs(self.pdf_dir, exist_ok=True)
        
    def generate_pdf(self, article):
        """生成PDF文件
        
        Args:
            article (dict): 文章信息，包含id, title, content, content_url, author, create_time
            
        Returns:
            str: PDF文件名
        """
        try:
            # 生成文件名
            filename = f"{article['id']}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
            pdf_path = os.path.join(self.pdf_dir, filename)
            
            # 生成HTML内容
            html_content = f"""
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <title>{article['title']}</title>
                <style>
                    body {{ font-family: Arial, sans-serif; margin: 40px; }}
                    h1 {{ color: #333; }}
                    .meta {{ color: #666; margin: 20px 0; }}
                    .content {{ line-height: 1.6; }}
                </style>
            </head>
            <body>
                <h1>{article['title']}</h1>
                <div class="meta">
                    <p>作者：{article['author']}</p>
                    <p>发布时间：{article['create_time']}</p>
                    <p>原文链接：{article['content_url']}</p>
                </div>
                <div class="content">
                    {article['content']}
                </div>
            </body>
            </html>
            """
            
            # 生成PDF
            HTML(string=html_content).write_pdf(pdf_path)
            
            logger.info(f"PDF生成成功: {pdf_path}")
            return filename
            
        except Exception as e:
            logger.error(f"生成PDF失败: {str(e)}")
            raise
            
    def clean_old_pdfs(self, days=30):
        """清理旧的PDF文件
        
        Args:
            days (int): 保留天数
            
        Returns:
            int: 清理的文件数量
        """
        try:
            count = 0
            now = datetime.now()
            
            for filename in os.listdir(self.pdf_dir):
                if not filename.endswith('.pdf'):
                    continue
                    
                file_path = os.path.join(self.pdf_dir, filename)
                file_time = datetime.fromtimestamp(os.path.getctime(file_path))
                
                if (now - file_time).days > days:
                    os.remove(file_path)
                    count += 1
                    
            logger.info(f"清理了 {count} 个PDF文件")
            return count
            
        except Exception as e:
            logger.error(f"清理PDF文件失败: {str(e)}")
            raise 